﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Text;
using System.Web.Security;
using System.Web.UI.WebControls;

public partial class account_Shoppingcart : System.Web.UI.Page
{
    /// <summary> 不要直接访问本字段，应用CurrentUserId访问。 </summary>
    private string userId;

    List<CartItem> cartItems;

    public string CurrentUserId
    {
        get
        {
            if (userId == null)
            {
                System.Diagnostics.Debug.Assert(Membership.GetUser() != null);
                userId = Membership.GetUser().ProviderUserKey.ToString();
            }

            return userId;
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        FillInCartItems();

        totalPriceLabel.Text = cartItems.Sum(item => item.Quantity * item.ProductDiscountedPrice).ToString(".##");

        if (cartItems.Count > 0)
        {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < cartItems.Count; i++)
            {
                sb.Append(cartItems[i].ProductId);
                sb.Append(",");
            }
            sb.Remove(sb.Length - 1, 1);
            productIdsField.Value = sb.ToString();
        }
    }

    private void FillInCartItems()
    {
        Contract.Ensures(cartItems != null);

        var connString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["ASPNETDBConnectionString"];
        if (connString == null)
            throw new ArgumentNullException("无法获取指定的数据库连接字符串。");


        cartItems = new List<CartItem>();
        using (SqlConnection connection = new SqlConnection(connString.ConnectionString))
        {
            connection.Open();

            SqlCommand command = new SqlCommand(
                string.Format(
                    @"
SELECT   [Shopping Cart].Quantity, vw_DiscountedProduct.id, vw_DiscountedProduct.name, vw_DiscountedProduct.Shop,
         vw_DiscountedProduct.coverPhoto, vw_DiscountedProduct.discountedPrice
FROM      [Shopping Cart] INNER JOIN
          vw_DiscountedProduct ON [Shopping Cart].productId = vw_DiscountedProduct.id
WHERE ([Shopping Cart].UserId = '{0}')   
",
                    CurrentUserId),
                connection);
            command.CommandType = System.Data.CommandType.Text;
            var reader = command.ExecuteReader();

            while (reader.Read())
            {
                cartItems.Add(new CartItem
                                  {
                                      Quantity = reader.GetInt32(0),
                                      ProductId = reader.GetInt32(1),
                                      ProductName = reader.GetString(2),
                                      ProductShop = reader.GetString(3),
                                      //CoverPhoto
                                      ProductDiscountedPrice = reader.GetDecimal(5)
                                  });
            }
        }
    }

    protected void cartItemsSource_Selecting(object sender, LinqDataSourceSelectEventArgs e)
    {
        e.Result = from c in cartItems.GroupBy(c => c.ProductShop)
                   select new { c.Key, It = c };
    }

    protected void deleteCartItem(object sender, GridViewDeleteEventArgs e)
    {
        var connString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["ASPNETDBConnectionString"];
        if (connString == null)
            throw new ArgumentNullException("无法获取指定的数据库连接字符串。");

        using (SqlConnection connection = new SqlConnection(connString.ConnectionString))
        {
            connection.Open();

            SqlCommand command = new SqlCommand(
                string.Format("delete from [shopping cart] where productId='{0}' and [userId]='{1}'", e.Keys[0], CurrentUserId),
                connection);
            command.CommandType = System.Data.CommandType.Text;
            int affectedRows = command.ExecuteNonQuery();
            Contract.Assert(affectedRows > 0, "数据库操作失败，该商品没有从数据库表中删除。请稍候再试。");
        }


    }

    public class CartItem
    {
        public int Quantity { get; set; }

        public string UserId { get; set; }

        public int ProductId { get; set; }

        public string ProductName { get; set; }

        public decimal ProductDiscountedPrice { get; set; }

        public string ProductShop { get; set; }

        public string CoverPhoto { get; set; }
    }

    protected void cartItemsSource_Deleting(object sender, LinqDataSourceDeleteEventArgs e)
    {

    }
    protected void payButton_Click(object sender, EventArgs e)
    {
        Response.Redirect(ResolveUrl("~/account/pay.aspx?source=shoppingcart"));
    }
}